
#include <iostream>
#include <errno.h>
#include <termios.h>
#include <unistd.h>
#include <cstdio>
#include <cstdlib>
#include <fcntl.h>
#include <cstring>
#include "serial.h"


using namespace std;


Serial::Serial()
{
	is_connected=false;
}


Serial::~Serial()
{
	
}

int Serial::Open(const char * device)
{
	int speed=B2400;
	int parity=0;
	
	is_connected=false;
	
	fd = open (device, O_RDWR | O_NOCTTY | O_NONBLOCK);
	
	if(fd<0)
	{
		cerr<<"Failed to open port "<<device<<endl;
		return -1;
	}
	
	struct termios tty;
	memset (&tty, 0, sizeof tty);
	if (tcgetattr (fd, &tty) != 0)
	{
			cerr<< "error "<<errno<<" from tcgetattr"<<endl;
			return -1;
	}

	cfsetospeed (&tty, speed);
	cfsetispeed (&tty, speed);

	tty.c_cflag = (tty.c_cflag & ~CSIZE) | CS8;     // 8-bit chars
	// disable IGNBRK for mismatched speed tests; otherwise receive break
	// as \000 chars
	tty.c_iflag &= ~IGNBRK;         // ignore break signal
	tty.c_lflag = 0;                // no signaling chars, no echo,
									// no canonical processing
	tty.c_oflag = 0;                // no remapping, no delays
	tty.c_cc[VMIN]  = 0;            // read doesn't block
	tty.c_cc[VTIME] = 5;            // 0.5 seconds read timeout

	tty.c_iflag &= ~(IXON | IXOFF | IXANY); // shut off xon/xoff ctrl

	tty.c_cflag |= (CLOCAL | CREAD);// ignore modem controls,
									// enable reading
	tty.c_cflag &= ~(PARENB | PARODD);      // shut off parity
	tty.c_cflag |= parity;
	tty.c_cflag &= ~CSTOPB;
	tty.c_cflag &= ~CRTSCTS;

	if (tcsetattr (fd, TCSANOW, &tty) != 0)
	{
			cerr<<"error "<<errno<<" from tcsetattr"<<endl;
			return -1;
	}
	
	/* disable blocking */
	/*
	memset (&tty, 0, sizeof tty);
	if (tcgetattr (fd, &tty) != 0)
	{
			cerr<<"error "<<errno<<" from tggetattr"<<endl;
			return -1;
	}

	tty.c_cc[VMIN]  = 0;
	tty.c_cc[VTIME] = 5;            // 0.5 seconds read timeout

	if (tcsetattr (fd, TCSANOW, &tty) != 0)
	{
			cerr<<"error "<<errno<<" setting term attributes"<<endl;
			return -1;
	}
*/
	is_connected=true;
	return 0;
}

int Serial::Read(uint8_t * data)
{
	return read (fd, data, 1);
}

void Serial::Write(uint8_t data)
{
	write(fd,&data,1);
}

void Serial::Close()
{
	if(is_connected)
	{
		close(fd);
	}
	is_connected=false;
}

bool Serial::IsConnected()
{
	return is_connected;
}
